# -*- coding: utf-8 -*-
if 'bpy' in locals():
	import imp
	imp.reload(easy_mmd_logger)
	imp.reload(import_pmx)
	imp.reload(export_pmx)
	imp.reload(import_pmd)
	imp.reload(export_pmd)
	imp.reload(import_mqo)
	imp.reload(export_mqo)
else:
	import logging
	import traceback
	import bpy
	import bpy_extras.io_utils
	from . import easy_mmd_logger
	from . import import_pmx
	from . import export_pmx
	from . import import_pmd
	from . import export_pmd
	from . import import_mqo
	from . import export_mqo
#
bl_info = {
	'name' : 'easy mmd tools',
	'author' : 'fuzhibo',
	'version' : (0,0,1),
	'blender' : (2, 61, 0),
	'location' : 'View3D > Tool Shelf > Easy MMD Panel;File > Import-Export',
	'description' : '''Easy MMD Tools based on meshio and blender_mmd_tools.''',
	'warning' : '''This project is based on two project:blender_mmd_tools(https://github.com/sugiany/blender_mmd_tools);pymeshio(https://github.com/ousttrue/pymeshio).If there are some bugs please email to mobilefzb@163.com''',
	'wiki_url' : 'http://git.oschina.net/mobilefzb/blender_plug_mode_factory',
	'tracker_url' : 'http://git.oschina.net/mobilefzb/blender_plug_mode_factory',
	'category' : 'Object',
}

class ImportPmd(bpy.types.Operator,bpy_extras.io_utils.ImportHelper):
	'''Import from PMD file format(.pmd)'''
	bl_idname = 'import_scene.mmd_pmd'
	bl_label = 'Import PMD'
	bl_options = {'UNDO'}
	filename_ext = '.pmd'
	#过滤的字符串
	filter_glob = bpy.props.StringProperty(
		default = '*.pmd', options = {'HIDDEN'})

	def execute(self, context):
		#日志初始化,self.filepath是导入的模型的路径
		easy_mmd_logger.log_init(self.filepath,logging.DEBUG)
		try:
			#**用来处理传递任意个有名字的参数，这些参数用dict来访问。
			import_pmd._execute(**self.as_keywords(
						ignore = ('filter_glob',)))
		except Exception as e:
			logging.debug(traceback.format_exc())
			self.report({'ERROR',str(e)})
		finally:
			easy_mmd_logger.log_uninit()
		return {'FINISHED'}

	@classmethod
	def menu_func(klass,self,context):
		self.layout.operator(klass.bl_idname,
			text = 'MikuMikuDance model (.pmd)',
			 icon = 'PLUGIN')
#这个是mmd模型的升级版格式
class ImportPmx(bpy.types.Operator,bpy_extras.io_utils.ImportHelper):
	'''Import from PMX Format(.pmx)(.pmd)'''
	bl_idname = 'import_scene.mmd_pmx_pmd'
	bl_label = 'Import PMX/PMD'
	bl_options = {'UNDO'}
	filename_ext = '.pmx;.pmd'
	filter_glob = bpy.props.StringProperty(
		default = '*.pmx;*.pmd', options = {'HIDDEN'})

	import_mesh = bpy.props.BoolProperty(
		name = 'import mesh',
		description = 'import polygon mesh',
		default = True)

	import_physics = bpy.props.BoolProperty(
		name = 'import physics objects',
		description = 'import rigid body and constraints',
		default = True)

	def execute(self,context):
		#日志初始化
		easy_mmd_logger.log_init(self.filepath,logging.DEBUG)
		try:
			import_pmx._execute(**self.as_keywords(ignore=('filter_glob',)))
		except Exception as e:
			logging.debug(traceback.format_exc())
			self.report({'ERROR',str(e)})
		finally:
			easy_mmd_logger.log_uninit()
		
		return {'FINISHED'}

	@classmethod
	def menu_func(klass,self,context):
		self.layout.operator(klass.bl_idname,
			text = 'MikuMikuDance model (.pmx)(.pmd)',
			icon = 'PLUGIN')

#这个是日本开发的一个叫做水杉的3D建模软件，这个是其文件格式
class ImportMqo(bpy.types.Operator,bpy_extras.io_utils.ImportHelper) :
	'''Import from MQO file format (.mqo)'''
	bl_idname = 'import_scene.metasequioa_mqo'
	bl_label = 'Import MQO'
	bl_options = {'UNDO'}
	filename_ext = '.mqo'
	filter_glob = bpy.props.StringProperty(
		default = '*.mqo', options = {'HIDDEN'})
	scale = bpy.props.FloatProperty(
		name = 'Scale',
		description = 'Scale the MQO by this value',
		min = 0.0001, max = 1000000.0,
		soft_min = 0.001, soft_max = 100.0, default = 0.1)

	def execute(self,context):
		#日志初始化
		easy_mmd_logger.log_init(self.filepath,logging.DEBUG)
		try:
			import_mqo._execute(**self.as_keywords(ignore = ('filter_glob',)))
		except Exception as e:
			logging.debug(traceback.format_exc())
			self.report({'ERROR',str(e)})
		finally:
			easy_mmd_logger.log_uninit()
		
		return {'FINISHED'}

	@classmethod
	def menu_func(klass,self,context):
		self.layout.operator(klass.bl_idname,
			text = "Metasequoia (.mqo)",
			icon = 'PLUGIN')

class ExportPmd(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
	'''Export to PMD file format (.pmd)'''
	bl_idname = 'export_scene.mmd_pmd'
	bl_label = 'Export PMD'

	filename_ext = '.pmd'
	filter_glob = bpy.props.StringProperty(
		default = '*.pmd', options = {'HIDDEN'})
	use_selection = bpy.props.BoolProperty(
		name = 'Selection Only', 
		description = 'Export selected objects only', 
		default = False)

	def execute(self, context):
		#日志初始化
		easy_mmd_logger.log_init(self.filepath,logging.DEBUG)
		try:
			export_pmd._execute(**self.as_keywords(
				ignore = ('check_existing', 'filter_glob', 'use_selection')))
		except Exception as e:
			logging.debug(traceback.format_exc())
			self.report({'ERROR',str(e)})
		finally:
			easy_mmd_logger.log_uninit()
		
		return {'FINISHED'}

	@classmethod
	def menu_func(klass, self, context):
		default_path = bpy.data.filepath.replace('.blend', '.pmd')
		self.layout.operator(klass.bl_idname,
			text = 'Miku Miku Dance Model(.pmd)',
			icon = 'PLUGIN').filepath = default_path

class ExportPmx(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
	'''Export to PMX file format (.pmx)'''
	bl_idname = 'export_scene.mmd_pmx'
	bl_label = 'Export PMX'

	filename_ext = '.pmx'
	filter_glob = bpy.props.StringProperty(
		default = '*.pmx', options = {'HIDDEN'})

	use_selection = bpy.props.BoolProperty(
		name = 'Selection Only', 
		description = 'Export selected objects only', 
		default = False)

	def execute(self, context):
		#日志初始化
		easy_mmd_logger.log_init(self.filepath,logging.DEBUG)
		try:
			export_pmx._execute(**self.as_keywords(
				ignore = ('check_existing', 'filter_glob', 'use_selection')))
		except Exception as e:
			logging.debug(traceback.format_exc())
			self.report({'ERROR',str(e)})
		finally:
			easy_mmd_logger.log_uninit()
		
		return {'FINISHED'}

	@classmethod
	def menu_func(klass, self, context):
		default_path = bpy.data.filepath.replace('.blend', '.pmx')
		self.layout.operator(klass.bl_idname,
			text = 'Miku Miku Dance Model(.pmx)',
			icon = 'PLUGIN').filepath = default_path

class ExportMqo(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
	'''Save a Metasequoia MQO file.'''
	bl_idname = 'export_scene.metasequioa_mqo'
	bl_label = 'Export MQO'
	filename_ext = '.mqo'
	filter_glob = bpy.props.StringProperty(
		default = '*.mqo', options = {'HIDDEN'})

	use_selection = bpy.props.BoolProperty(
		name = 'Selection Only', 
		description = 'Export selected objects only', 
		default = False)

	scale = bpy.props.FloatProperty(
		name = 'Scale',
		description = 'Scale the MQO by this value',
		min = 0.0001, max = 1000000.0,
		soft_min = 0.001, soft_max = 100.0, default = 10.0)

	apply_modifier = bpy.props.BoolProperty(
		name = 'ApplyModifier',
		description = 'Would apply modifiers',
		default = False)

	def execute(self, context):
		#日志初始化
		easy_mmd_logger.log_init(self.filepath,logging.DEBUG)
		try:
			export_mqo._execute(**self.as_keywords(
				ignore = ('check_existing', 'filter_glob', 'use_selection')))
		except Exception as e:
			logging.debug(traceback.format_exc())
			self.report({'ERROR',str(e)})
		finally:
			easy_mmd_logger.log_uninit()
		
		return {'FINISHED'}

	@classmethod
	def menu_func(klass, self, context):
		default_path = bpy.data.filepath.replace('.blend', '.mqo')
		self.layout.operator(klass.bl_idname,
			text = 'Metasequoia (.mqo)',
			icon = 'PLUGIN').filepath = default_path

def register():
	#导入这几个菜单的实现
	bpy.utils.register_module(__name__)
	bpy.types.INFO_MT_file_import.append(ImportPmd.menu_func)
	bpy.types.INFO_MT_file_import.append(ImportPmx.menu_func)
	bpy.types.INFO_MT_file_import.append(ImportMqo.menu_func)
	bpy.types.INFO_MT_file_export.append(ExportPmd.menu_func)
	bpy.types.INFO_MT_file_export.append(ExportPmx.menu_func)
	bpy.types.INFO_MT_file_export.append(ExportMqo.menu_func)
	#blender_tool的工具集合注册到这里来

def unregister():
	bpy.utils.unregister_module(__name__)
	bpy.types.INFO_MT_file_import.remove(ImportPmd.menu_func)
	bpy.types.INFO_MT_file_import.remove(ImportPmx.menu_func)
	bpy.types.INFO_MT_file_import.remove(ImportMqo.menu_func)
	bpy.types.INFO_MT_file_export.remove(ExportPmd.menu_func)
	bpy.types.INFO_MT_file_export.remove(ExportPmx.menu_func)
	bpy.types.INFO_MT_file_export.remove(ExportMqo.menu_func)


if __name__ == '__main__':
 	register()
